// https://www.lintcode.com/problem/sort-list/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: You should return the head of the sorted linked list, using constant space complexity.
     */
    public ListNode sortList(ListNode head) {
        // write your code here
        if ((head == null) || (head.next == null)) {
            return head;
        }
        ListNode prev = null;
        ListNode one = head;
        ListNode two = head;
        while ((one != null) && (two != null)) {
            two = two.next;
            if (two != null) {
                two = two.next;
                prev = one;
                one = one.next;
            } else {
                break;
            }
        }
        ListNode new_head = prev.next; // 后半段链表
        prev.next = null;
        return mergeList(sortList(head), sortList(new_head));
    }

    protected ListNode mergeList(ListNode left, ListNode right) {
        ListNode head = null;
        ListNode tail = null;
        while ((left != null) && (right != null)) {
            ListNode node;
            if (left.val <= right.val) {
                node = left;
                left = left.next;
            } else {
                node = right;
                right = right.next;
            }
            if (head == null) {
                head = node;
            } else {
                tail.next = node;
            }
            tail = node;
            tail.next = null;
        }
        if (head == null) {
            head = (left != null) ? left : right;
        } else {
            tail.next = (left != null) ? left : right;
        }
        return head;
    }
}